<script setup>
import {ref, provide, onBeforeMount, watchEffect} from 'vue'
import AddProductCategory from "@/views/index/product/components/AddProductCategory.vue";
import {delProductCategoryAPI, delProductCategorySubAPI, getProductCategoryPageAPI} from "@/api/product.js";
import AddProductCategorySub from "@/views/index/product/components/AddProductCategorySub.vue";
import UpdateProductCategory from "@/views/index/product/components/UpdateProductCategory.vue";
import UpdateProductCategorySub from "@/views/index/product/components/UpdateProductCategorySub.vue";
import {elErrorMessageTip} from "@/utils/MessageTipUtils.js";

const env = import.meta.env
const PRODUCT_CATEGORY_NAME_MAX_LEN = env.VITE_PRODUCT_CATEGORY_NAME_MAX_LEN
const PRODUCT_CATEGORY_CODE_MAX_LEN = env.VITE_PRODUCT_CATEGORY_CODE_MAX_LEN

// 分页数据与条件
const current = ref(1)
// 每页数据个数
const pageSize = ref(10)
const productCategoryNameMatch = ref('')
const productCategoryCodeMatch = ref('')
const pageCnt = ref(0)
// 总页数
const size = ref(0)
const data = ref([])
// 下拉选择选项
const selectOptions = [
  {label: '全部', value: ''},
  {label: '禁用', value: true},
  {label: '开放', value: false},
]
// 下拉选择
const selectValue = ref(null)

// 获取分页商品分类
const getProductCategoryPage = async (current_, pageSize_, disabled_ = null, nameMatch_ = null, codeMatch_ = null) => {
  const res = await getProductCategoryPageAPI(current_, pageSize_, disabled_, nameMatch_, codeMatch_)
  if (res === null) return
  current.value = res.current
  pageSize.value = res.pageSize
  pageCnt.value = res.pageCnt
  size.value = res.size
  data.value = res.data
}

// 初始查询
onBeforeMount(async () => {
  await getProductCategoryPage(current.value, pageSize.value)
})

// 获取商品分类信息（条件查询）
const searchByCondition = async () => {
  await getProductCategoryPage(current.value, pageSize.value, selectValue.value, productCategoryNameMatch.value, productCategoryCodeMatch.value)
}

// 分页每页数据大小改变
const handlePageSizeChange = async (val) => {
  pageSize.value = val
  await searchByCondition()
}
// 当前页发生变化
const handleCurrentChange = async (val) => {
  current.value = val
  await searchByCondition()
}

// 新增商品分类是否显示
const addProductCategoryVisible = ref(false)
// 显示
const showAddProductCategory = () => {
  addProductCategoryVisible.value = true
}
// 传递给子组件
provide('addProductCategory', {addProductCategoryVisible, searchByCondition})

// 新增二级商品分类是否显示
const addProductCategorySubVisible = ref(false)
// 显示
const showAddProductCategorySub = () => {
  addProductCategorySubVisible.value = true
}
provide('addProductCategorySub', {addProductCategorySubVisible, searchByCondition, data})

// 修改商品分类
const productCategory = ref({})
const updateProductCategoryVisible = ref(false)
const showUpdateProductCategory = (idx) => {
  productCategory.value = data.value[idx]
  updateProductCategoryVisible.value = true
}
provide('updateProductCategory', {updateProductCategoryVisible, searchByCondition, productCategory})

// 修改二级商品分类
const productCategorySub = ref({})
const updateProductCategorySubVisible = ref(false)
const showUpdateProductCategorySub = (idx, i_idx) => {
  productCategorySub.value = data.value[idx].subs[i_idx]
  updateProductCategorySubVisible.value = true
}
provide('updateProductCategorySub', {updateProductCategorySubVisible, searchByCondition, productCategorySub})

// 删除一级商品分类
const delProductCategory = ref({})
const delProductCategoryVisible = ref(false)
const delPcSelectValue = ref('')
const delPcSectOptions = ref([])
const showDelProductCategory = (idx) => {
  delPcSectOptions.value = []
  delProductCategory.value = data.value[idx]
  data.value.forEach(item => {
    if (item.id === delProductCategory.value.id) return
    delPcSectOptions.value.push({value: item.id, label: item.name})
  })
  delProductCategoryVisible.value = true
}
const delProductCategoryHandler = async () => {
  if (delPcSelectValue.value.length <= 0) {
    elErrorMessageTip("请先选择二级分类要转移至的一级分类")
    return
  }
  const res = await ElMessageBox.confirm(
      `是否确认商品分类：${delProductCategory.value.name}`,
      '删除商品分类',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    // 执行删除
    return await delProductCategoryAPI(delProductCategory.value.id, delPcSelectValue.value)
  }).catch(() => {
    return false
  })
  // 成功
  if (res) {
    delProductCategory.value = {}
    delProductCategoryVisible.value = false
    delPcSelectValue.value = ''
    delPcSectOptions.value = []
    await searchByCondition()
  }
}

// 删除二级商品分类
const delProductCategorySub = ref({})
const delProductCategorySubVisible = ref(false)
const delSubPcSelectValue = ref('')
const delSubPcSectOptions = ref([])
const delSubPcsSelectValue = ref('')
const delSubPcsSectOptions = ref([])
const showDelProductCategorySub = (idx, idx_sub) => {
  delProductCategorySub.value = data.value[idx].subs[idx_sub]
  delSubPcSectOptions.value = []
  data.value.forEach(
      productCategory => {
        const subs = productCategory.subs.filter(item => item.id !== delProductCategorySub.value.id)
        if (subs.length > 0) {
          delSubPcSectOptions.value.push({
            label: productCategory.name,
            value: productCategory.id
          })
        }
      }
  )
  delProductCategorySubVisible.value = true
}
watchEffect(() => {
  if (delSubPcSelectValue.value !== '') {
    data.value.forEach(
        productCategory => {
          if (productCategory.id === delSubPcSelectValue.value) {
            delSubPcsSectOptions.value = productCategory.subs.map(
                item => ({
                  label: item.name,
                  value: item.id
                })
            )
          }
        }
    )
  } else {
    delSubPcsSelectValue.value = ''
    delSubPcsSectOptions.value = []
  }
})
const delProductCategorySubHandler = async () => {
  if (delSubPcSelectValue.value === '' || delSubPcsSelectValue.value === '') {
    elErrorMessageTip("请选择该分类下商品转移至何处")
    return
  }
  const res = await ElMessageBox.confirm(
      `是否确认二级商品分类：${delProductCategorySub.value.name}`,
      '删除二级商品分类',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    // 执行删除
    return await delProductCategorySubAPI(
        delProductCategorySub.value.id,
        delSubPcSelectValue.value,
        delSubPcsSelectValue.value
    )
  }).catch(() => {
    return false
  })
  // 成功
  if (res) {
    delProductCategorySubVisible.value = false
    await searchByCondition()
  }
}

// 为表格的禁用行添加禁用类名
const tableRowClassName = ({row: auth}) => {
  if (auth.disabled === true) return 'disabled-row'
  return ''
}
</script>

<template>
  <div class="product-category w-full">
    <el-affix target=".product-category" :offset="80">
      <div class="p-4 glass-container flex justify-between items-center">
        <div class="flex justify-start items-center">
          <el-select v-model="selectValue" class="" placeholder="是否禁用">
            <el-option
                v-for="item in selectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <div>
            <el-input class="ipt" v-model="productCategoryNameMatch" clearable
                      :maxlength="PRODUCT_CATEGORY_NAME_MAX_LEN"
                      show-word-limit placeholder="请输入商品分类名称"/>
          </div>
          <div>
            <el-input class="ipt" v-model="productCategoryCodeMatch" clearable
                      :maxlength="PRODUCT_CATEGORY_CODE_MAX_LEN"
                      show-word-limit placeholder="请输入商品分类编码"/>
          </div>
          <el-button type="primary" plain @click="searchByCondition">搜索</el-button>
        </div>
        <div>
          <el-button type="primary" plain @click="showAddProductCategory">新增商品分类</el-button>
          <el-button type="primary" plain @click="showAddProductCategorySub">新增二级商品分类</el-button>
        </div>
      </div>
    </el-affix>
    <div class="w-full">
      <div class="mt-8 w-full h-full pl-4 pr-4 pb-4 glass-container">
        <el-card class="p-4 mt-4 rounded-md bg-white"
                 v-for="(item, idx) in data"
                 :key="item.id">
          <template #header>
            <el-descriptions :column="6" direction="vertical" border>
              <el-descriptions-item label="商品一级分类 ID">{{ item.id }}</el-descriptions-item>
              <el-descriptions-item label="商品一级分类名称">{{ item.name }}</el-descriptions-item>
              <el-descriptions-item label="商品一级分类编码">{{ item.code }}</el-descriptions-item>
              <el-descriptions-item label="是否禁用">
                <el-tag class="ml-2" type="warning" v-if="item.disabled">禁用</el-tag>
                <el-tag class="ml-2" type="success" v-else>开放</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="商品一级分类描述">{{ item.description }}</el-descriptions-item>
              <el-descriptions-item label="操作">
                <el-button type="info" plain size="small" @click="showUpdateProductCategory(idx)">修改</el-button>
                <el-button type="danger" plain size="small" @click="showDelProductCategory(idx)">删除</el-button>
              </el-descriptions-item>
            </el-descriptions>
          </template>
          <template #default>
            <el-table class="mt-4"
                      style="width: 100%"
                      :data="item.subs"
                      :row-class-name="tableRowClassName">
              <el-table-column prop="id" label="ID" width="100"/>
              <el-table-column prop="name" label="商品二级分类名称" width="200"/>
              <el-table-column prop="code" label="商品二级分类编码" width="300"/>
              <el-table-column prop="disabled" label="是否禁用" width="150">
                <template #default="scoped">
                  <el-tag class="ml-2" type="warning" v-if="item.subs[scoped.$index].disabled">禁用</el-tag>
                  <el-tag class="ml-2" type="success" v-else>开放</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" width="640"/>
              <el-table-column fixed="right" label="操作" width="150">
                <template #default="scope">
                  <el-button type="info" plain size="small" @click="showUpdateProductCategorySub(idx, scope.$index)">
                    修改
                  </el-button>
                  <el-button type="danger"
                             plain
                             size="small"
                             @click="showDelProductCategorySub(idx, scope.$index)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-card>
      </div>
    </div>
  </div>
  <!-- 分页 -->
  <div class="glass-container fixed right-6 bottom-2 p-4 flex justify-end items-center">
    <el-pagination
        v-model:current-page="current"
        v-model:page-size="pageSize"
        :page-sizes="[1, 10, 20, 30, 40]"
        :page-count="pageCnt"
        layout="sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 新增商品分类 -->
  <AddProductCategory></AddProductCategory>
  <AddProductCategorySub :data="data"></AddProductCategorySub>
  <UpdateProductCategory></UpdateProductCategory>
  <UpdateProductCategorySub :data="data"></UpdateProductCategorySub>
  <!-- 删除一级分类 -->
  <el-dialog
      v-model="delProductCategoryVisible"
      title="删除一级商品分类"
      width="30%"
  >
    <el-form label-position="right" label-width="170px">
      <el-form-item label="商品分类 ID">{{ delProductCategory.id }}</el-form-item>
      <el-form-item label="商品分类名称">{{ delProductCategory.name }}</el-form-item>
      <el-form-item label="商品分类编码">{{ delProductCategory.code }}</el-form-item>
      <el-form-item label="该分类下二级分类转移至">
        <el-select v-model="delPcSelectValue" class="" placeholder="选择二级分类要转移到的一级商品分类">
          <el-option
              v-for="item in delPcSectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div class="flex justify-end items-center">
      <el-button type="primary" @click="delProductCategoryHandler">删除商品分类</el-button>
    </div>
  </el-dialog>
  <!-- 删除二级分类 -->
  <el-dialog
      v-model="delProductCategorySubVisible"
      title="删除二级商品分类"
      width="30%"
  >
    <el-form label-position="right" label-width="170px">
      <el-form-item label="商品二级分类 ID">{{ delProductCategorySub.id }}</el-form-item>
      <el-form-item label="商品二级分类名称">{{ delProductCategorySub.name }}</el-form-item>
      <el-form-item label="商品二级分类编码">{{ delProductCategorySub.code }}</el-form-item>
      <el-form-item label="该分类下商品转移至">
        <div>
          <el-select v-model="delSubPcSelectValue" class="" placeholder="选择商品要转移到的一级商品分类">
            <el-option
                v-for="item in delSubPcSectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <div>
          <el-select :disabled="delSubPcsSectOptions <= 0"
                     v-model="delSubPcsSelectValue"
                     class=""
                     placeholder="选择商品要转移到的二级商品分类">
            <el-option
                v-for="item in delSubPcsSectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
      </el-form-item>
    </el-form>
    <div class="flex justify-end items-center">
      <el-button type="primary" @click="delProductCategorySubHandler">删除商品分类</el-button>
    </div>
  </el-dialog>
</template>

<style lang="scss">
// 表格禁用行样式
.el-table .disabled-row {
  --el-table-tr-bg-color: #f4f4f5;
  --el-table-row-hover-bg-color: #f4f4f5;
  color: #cbcccf;
}
</style>